# -*- coding: utf-8 -*-
"""

@author: gcq
"""

import pandas as pd
import numpy as np
from fuzzywuzzy import fuzz
import requests
import pymysql
from sqlalchemy import create_engine


class FillPlaceText(object):
    """
    """

    def fill_gd(self):
        df = pd.read_excel("01-高德清洗v-01.xlsx", sheet_name = 0)
        #df = df[(str(df['is_accurate']) == 'nan') | (df['is_accurate'] == '否') | (df['is_accurate'] == '无信息')]
        #df = df[df['is_accurate'].isin(['nan', '否', '无信息'])]
        size = len(df)
        self.fill_gd_info(df)
        #df['temp'] = df.apply(self.get_info, axis = 1)
        #df['city_match'] = df.apply(lambda x:fuzz.partial_ratio(str(x['city_name']),str(x['gd_city'])),axis = 1)
        print("@@@errorCount:", self.errorCount)
        try:
            df.to_excel("01-高德清洗v-02.xlsx", sheet_name="Sheet1", encoding='utf-8')
        except Exception as er:
            print(er)

    errorCount = 0;

    def fill_gd_info(self, df):
        for i in range(len(df)):
            try:
                row = df.iloc[i]
                rest = self.get_info(row)
                if rest is None :
                    continue
                if len(rest[0]) > 0 :
                    df.loc[i, 'gd_city'] = rest[0]
                    df.loc[i, 'gd_county'] = rest[1]
                    df.loc[i, 'gd_office_name'] = rest[2]
                    df.loc[i, 'gd_lnglat'] = rest[3]
                df.loc[i, 'match'] = str(rest[4])
                df.loc[i, 'type'] = str(rest[5])
                df.loc[i, 'remark'] = rest[7]
                #break
            except Exception as e:
                print (e)

    def get_info(self, row):
        #is_accurate
        is_accurate = str(row['is_accurate'])
        if (is_accurate == '是' or is_accurate == '非住宅' or is_accurate.__contains__('修改')) :
            return None#(str(row['gd_city']), str(row['gd_county']), str(row['gd_office_name']), str(row['gd_lnglat']), 100, 'type', '是', '已核对')

        city_name = str(row['city_name'])
        county_name = str(row['county_name'])
        newest_name = str(row['newest_name'])
        alias = str(row['alias']).replace("别名：", '')
        address = str(row['address'])

        url_str="https://restapi.amap.com/v3/place/text?key=7aee39e5e143265d0359077beb64d705&extensions=all&output=JSON&offset=10&page=1"#&types=120000
        url = url_str + "&keywords=" + newest_name + "&city=" + city_name
        res = requests.get(url).json()

        status = res['status']
        info = res['info']
        if status == 0 :
            print(info)

        count = res['count']
        pois = res['pois']
        size = len(pois)
        if size > 0 :
            list = []
            for poi in pois :
                try :
                    name = poi['name']
                    try :
                        gd_address = poi['address']
                    except Exception as ex:
                        gd_address = ''
                    location = poi['location']
                    cityname = poi['cityname']
                    adname = poi['adname']
                    type = poi['type']
                    if len(type) > 0 :
                        type = str(poi['type']).split(';')[0]
                    gd_alias = str(poi['alias']).split("|")
                    gd_alias.sort()
                    gd_alias = ''.join(gd_alias)

                    name_ratio = fuzz.partial_ratio(newest_name, name)
                    if name_ratio == 100 :
                        return (cityname, adname, name, location, name_ratio, type, '是', '【名称】VS【名称】相似度%s%%'%(name_ratio))
                    else :
                        list.append((cityname, adname, name, location, name_ratio, type, '否', '【名称】VS【名称】相似度%s%%'%(name_ratio)))
                    # 跟【别名】进行比较
                    alias_ratio = fuzz.partial_ratio(newest_name, gd_alias)
                    if alias_ratio == 100 :
                        return (cityname, adname, name, location, alias_ratio, type, '是', '【名称】VS【别名】相似度%s%%'%(alias_ratio))
                    else :
                        list.append((cityname, adname, name, location, alias_ratio, type, '否', '【名称】VS【别名】相似度%s%%'%(alias_ratio)))
                except Exception as er:
                    print('@@@@@@@',er)
                    list.append(('', '', '', '', 0, '', '否', '异常信息%s'%(er)))

            if len(list) > 0 :
                list.sort(key = lambda x:x[4], reverse = True )
                #print("排序列表：", list)
                return list.pop(0)
            else :
                return ('', '', '', '', 0, '', '否', 'size：%s'%(size))
        else :
            self.errorCount += 1;
            return ('', '', '', '', 0, '', '否', 'city_name：%s, newest_name：%s'%(city_name, newest_name))


if __name__ == "__main__":
    obj = FillPlaceText()
    obj.fill_gd()
    #插入数据#
    print(1111111111)
